<template>
	<el-tree-select
		clearable
		:check-strictly="checkStrictly"
		:default-expand-all="defaultExpandAll"
		:multiple="multiple"
		v-model="value"
		:node-key="nodeKey"
		:props="props.props"
		:data="treeList"
		:render-after-expand="false"
		:show-checkbox="showCheckbox"
		:highlight-current="true"
		:placeholder="placeholder"
	></el-tree-select>
</template>

<script lang="ts" setup name="DxMenuSelect">
import { onMounted, onUnmounted, ref, watch, inject } from 'vue';
import { axios } from '@/uni_modules/dx-admin/api/index';
import { arrayToTree } from '@/uni_modules/dx-admin/libs/utils';
const props = withDefaults(
	defineProps<{
		modelValue: any;
		url: string;
		funcName?: string;
		params?: any;
		props?: any;
		nodeKey?: string;
		parentKey?: string;
		placeholder?: string;
		checkStrictly?: boolean;
		defaultExpandAll?: boolean;
		multiple?: boolean;
		showCheckbox?: boolean;
		getListAfter?: Function;
	}>(),
	{
		funcName: 'dx-func-admin',
		nodeKey: '',
		parentKey: 'parent_id',
		checkStrictly: true,
		defaultExpandAll: true,
		multiple: false,
		showCheckbox: false,
		params: {},
		props: {
			label: 'name',
		},
	}
);
const value = ref('');
watch(
	() => props.modelValue,
	(newVal) => {
		value.value = newVal;
	}
);
const dxLayerFormShowId = inject('dxLayerFormShowId', '');
// 绑定关系
const $emit = defineEmits(['update:modelValue']);
watch(value, (newVal) => {
	$emit('update:modelValue', newVal || '');
});
const treeList = ref<any>([]);
const getTreeList = function () {
	axios.send(props.url, props.funcName, props.params).then(({ code, data, message }) => {
		if (code === 1000) {
			data = arrayToTree(data, props.nodeKey, props.parentKey);
			if (typeof props.getListAfter === 'function') {
				data = props.getListAfter(data);
			}
			treeList.value = data;
		} else {
			ElMessage.error(message);
		}
	});
};
getTreeList();

onMounted(() => {
	if (dxLayerFormShowId) uni.$on(dxLayerFormShowId, getTreeList);
});
onUnmounted(() => {
	if (dxLayerFormShowId) uni.$off(dxLayerFormShowId, getTreeList);
});
</script>
